$(document).ready(function() 
{


// Global Variable ================================================================
	var range = document.createRange();

// Event Processing ===============================================================
	$('.popup-control').on('click', function(e) {
		e.stopPropagation();
	});

	$('.wrapper.content').on('click', function(e) {
		e.stopPropagation();
		// unselect();
	});

	$(document).click(function() {

		$('.popup-control').hide();
		unselect();
	});

	$('#tag-form .is-location').click(function() {
		if ($('#tag-form .is-location').is(':checked')) {
			$('#tag-form .location').show('fast');
		}
		else $('#tag-form .location').hide('fast');
	});

	$('#tag-form .location select[name="local"]').change(function() {
		$('#tag-form .location .child').remove();
		if(this.value != 'null') {
			$.ajax({
				type: "POST",
				url: '/openlibraryonline/book/ajax_child_location/',
				data: ({
					parent: this.value
				}),
				success: function(data) {
					if(data != '')
						$('#tag-form .location').append(data);
				}
			});
		}
		// alert(this.value);
	});

// Add tag processing ======================================================
	$('#tag-form .submit').click(function(e) {
		e.preventDefault();

		tag_content = $('#tag-form .text').val();
		local = $('#tag-form .location:last-child').val();

		if(tag_content == '') 
		{
			$('.popup-control').hide();
			alert(local);
			alert('Vui lòng nhập nội dung tag');
			return;
		}

		alert(local);
		$.ajax({
			type: "POST",
			url: '/openlibraryonline/book/add_tag/',
			data: ({
				book: book_id,
				chap: chap_id,
				content: tag_content,
				location: local,
			}),
			success: function(data) {
				arr = data.split('-');
				if(arr[0] == 'success') 
				{
					$('.echoTag').removeClass();	
					addTagsToSelect('tag ' + arr[1]);
					alert('Thêm tag thành công: \n' + arr[1]);

					modifyBook();
				}
				else alert('Thêm tag thất bại: \n'+ data);
			},
			error: function() {
				alert('Kết nối thất bại');
			}
		});

		//=============================================================

		// Call ajax to modify in XHTML File
		modifyBook = function() 
		{
			var content = $('section .wrapper.content').html();
			$.ajax({
				type: "POST",
				url: '/openlibraryonline/book/book_modify/',
				data: ({
					link: link_chap,
					content: content.toString(),
				}),
				success: function(data) {
					$(".result .wrapper").html(data);
					console.log(data);
					// alert('Edit thanh cong' + link_chap);
				}
			});
		}

		//=============================================================

		$('.popup-control').hide('fast');
	});

//====================================================================================
	// Watch tag content
	$('span.tag').click(function() {
		idtag = $(this).attr('class').split(' ')[1];
		if(idtag != '') {
			$.ajax({
				type: "POST",
				url: '/openlibraryonline/book/get_tag_content/',
				data: ({
					tag: idtag
				}),
				success: function(data) {
					alert(data);
				}
			});
		}
	});

//====================================================================================
	$(".wrapper.content").bind("mouseup", function(e) {
		unselect();

		range = document.getSelection().getRangeAt(0);
		var textContent = range.toString();	
		// alert(textContent);
		$('.popup-control').hide();

		if(textContent == '') $('.popup-control').hide();
		else 
		{
			$('.popup-control').css({
				'left' : e.pageX,
				'top' : e.pageY + 70,
			});
			$('.popup-control').show('medium');

			addTagsToFile('selected');
		}
	});


	// ==============================================================
	// ==============================================================
	// ==============================================================

	function unselect() {
		$('.wrapper.content .selected').each(function() {
			$(this).replaceWith(this.childNodes);
		});
	}
	function addTagsToSelect(arg) {
		$('.wrapper.content .selected').each(function() {
			$(this).removeClass('selected');			
			$(this).addClass(arg);
			// $(this).removeClass('selected');
		});
	}

	function addTagsToFile(arr) {
		console.log('Range: ' + range.toString());
		console.log('StarRangeContainer \t ' + range.startContainer.data);

		var listNode = [];
		//-----------
		r = document.createRange();
		r.selectNode(range.startContainer);

		console.log('r-innerContainer \t ' + r.startContainer.innerHTML + ' - '  + r.startContainer);

		startNode = r.startContainer;
		tgName = startNode.tagName;
		while (tgName.toUpperCase() != 'P' && tgName.toUpperCase() != 'DIV') 
		{
			startNode = startNode.parentNode;
			tgName = startNode.tagName;
		}
		console.log('StartNode');
		console.log(startNode);

		listNode.push(startNode);

		//-------------

		console.log(' ');
		console.log('Range: ' + range.toString());
		console.log('EndRangeContainer \t ' + range.endContainer.data);

		r = document.createRange();
		r.selectNode(range.endContainer);

		console.log('r-innerContainer \t ' + r.startContainer.innerHTML + ' - '  + r.startContainer);

		endNode = r.startContainer;
		tgName = endNode.tagName;
		while (tgName.toUpperCase() != 'P' && tgName.toUpperCase() != 'DIV') {
			endNode = endNode.parentNode;
			tgName = endNode.tagName;
		}

		console.log('EndNode');
		console.log(endNode); console.log(' ');
		console.log('Is different: ' + startNode != endNode);

		//---------------
		if(startNode != endNode) 
		{
			listNode.push(endNode);

			parent = startNode.parentNode;
			// console.log(parent);
			betweenNodes = parent.childNodes;
			for (i = 0; i < betweenNodes.length; i++) {
				if(betweenNodes[i] == startNode) {
					i++;
					while (betweenNodes[i] != endNode) {
						console.log(betweenNodes[i]);
						listNode.push(betweenNodes[i]);
						i++;
					}
					break;
				}
			}
		}

		console.log(listNode);
		for(i = 0; i < listNode.length; i++) {
			$(listNode[i]).wrapInner('<span class="'+ arr +'"></span>');
		}
	}
});

// ======================================================================
	